<?php
namespace app\models;

use laiq\base\Model;
use laiq\db\Connection;

class ArticleModel extends Model
{
    protected $table = 'article';
    const STATUS_SHOW = 0;
    const STATUS_HIDE = 1;


    public function search($keyword)
    {
        $sql = "select * from `$this->table` where `item_name` like :keyword";
        $sth = Connection::pdo()->prepare($sql);
        $sth = $this->formatParam($sth, ['keyword' => "%$keyword%"]);
        $sth->execute();

        return $sth->fetchAll();
    }

    /**
     * 分页获取文章列表
     *
     * @param integer $limit
     * @param integer $offset
     * @return array 文章列表
     */
    public function findPosts($limit = 20, $offset = 0, $order = [])
    {
        $rows = $this->select($this->table, '*', [
            'id[>]' => $offset,
            'LIMIT' => $limit
        ]);
        return $rows;
    }

    public function findPost($postId)
    {
        if (!$postId) {
            throw new Exception('Miss Param');
        }
        $this->where('id', $postId, '=')->limit(1);
        $ret = $this->findOne();
        return $ret;
    }

    /**
     * 增加文章阅读量
     *
     * @param int $postId 文章ID
     * @return int 1=success 0=fail
     */
    public function incRead($postId)
    {
        if (!$postId) {
            throw new Exception('Miss Param');
        }
        $sql = sprintf("update `$this->table` set `read`=`read`+1 where id = %d", $postId);
        $ret = $this->exec($sql);
        return $ret;
    }

    /**
     * 获取推荐文章列表 
     *
     * @param integer $limit
     * @return void
     */
    public function findRecommend($limit = 4)
    {
        $rows = $this->select($this->table, '*', [
            'recommend' => 1,
            'LIMIT' => $limit
        ]);
        return $rows;
    }

    /**
     * 获取阅读量最多的文章
     *
     * @param integer $limit
     * @return array
     */
    public function findHots($limit = 5)
    {
        $rows = $this->select($this->table, '*', [
            'LIMIT' => $limit,
            "ORDER" => ["read" => "DESC"]
        ]);
        return $rows;
    }


    public function getCount(array $where)
    {
        return parent::count($this->table, $where);
    }
}